<template>
    <view class="order-container">
        <!-- 订单分类栏 -->
        <view class="category-bar">
            <view v-for="category in categories" :key="category.value" class="category-item"
                :class="{ active: params.orderState === category.value }" @click="changeCategory(category.value)">
                <text class="category-text">{{ category.label }}</text>
            </view>
        </view>

        <!-- 订单列表 -->
        <view class="order-list">
            <view v-if="loading" class="loading-container">
                <text>加载中...</text>
            </view>

            <view v-else-if="orders.length === 0" class="empty-container">
                <text>暂无订单</text>
            </view>

            <view v-else class="order-card" v-for="order in orders" :key="order.orderId">
                <!-- 订单头部信息 -->
                <view class="order-header">
                    <view class="order-type">
                        <text class="type-tag">{{ orderTypeMap.get(order.orderType) }}</text>
                    </view>
                    <view class="order-status">
                        <text class="status-text">{{ orderStatusMap.get(order.orderState) }}</text>
                    </view>
                </view>

                <!-- 订单基本信息 -->
                <view class="order-info">
                    <view class="info-row">
                        <text class="info-label">订单号：</text>
                        <text class="info-value">{{ order.orderNumber }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">车牌号：</text>
                        <text class="info-value">{{ order.plateNumber || '-' }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">订单时间：</text>
                        <text class="info-value">{{ formatTime(order.createTime) }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">服务开始时间：</text>
                        <text class="info-value">{{ formatTime(order.serviceStartTime) }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">开始行程时间：</text>
                        <text class="info-value">{{ formatTime(order.startRouteTime) }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">服务结束时间：</text>
                        <text class="info-value">{{ formatTime(order.serviceEndTime) }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">到达目的地时间：</text>
                        <text class="info-value">{{ formatTime(order.arriveDestinationTime) }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">乘客姓名：</text>
                        <text class="info-value">{{ order.passengerName || '-' }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">乘客手机号：</text>
                        <text class="info-value phone" @click="phone(order.passengerMobile)">
                            {{ order.passengerMobile || '-' }}</text>
                    </view>
                    <view v-if="order.flightNumber" class="info-row">
                        <text class="info-label">航班号：</text>
                        <text class="flight-number">{{ order.flightNumber }}</text>
                    </view>
                    <view v-if="order.trainNumber" class="info-row">
                        <text class="info-label">车次号：</text>
                        <text class="flight-number">{{ order.trainNumber }}</text>
                    </view>
                    <view v-if="order.confirmArrivalPickUpPointTime" class="info-row">
                        <text class="info-label">确认到达上车点时间：</text>
                        <text class="info-value">{{ formatTime(order.confirmArrivalPickUpPointTime) }}</text>
                    </view>
                    <view class="info-row">
                        <text class="info-label">到达上车点：</text>
                        <view class="flex info-value">
                            <image :src="'http://8.155.170.55' + item.filePath"
                                v-for="item in order.fileResponseList.filter(x => x.orderNode == 1)"
                                :key="item.fileName" @click="previewImage(item.filePath, order.fileResponseList, 1)"
                                class="img-info" mode="aspectFit" />
                        </view>
                    </view>
                    <view class="info-row">
                        <text class="info-label">到达目的地：</text>
                        <view class="flex info-value">
                            <image :src="'http://8.155.170.55' + item.filePath" class="img-info"
                                v-for="item in order.fileResponseList.filter(x => x.orderNode != 1)"
                                :key="item.fileName" @click="previewImage(item.filePath, order.fileResponseList, 2)"
                                mode="aspectFit" />
                        </view>
                    </view>
                    <!-- <view class="info-row">
                        <text class="info-label">司机价格</text>
                        <text class="info-value">{{ order.driverShowPrice }}</text>
                    </view> -->
                </view>

                <!-- 行程路线 -->
                <view class="route-info">
                    <view class="location-item">
                        <view class="location-point start-point"></view>
                        <view class="location-content">
                            <text class="location-text">{{ order.departureAddress }}</text>
                        </view>
                    </view>
                    <view class="location-line"></view>
                    <view class="location-item">
                        <view class="location-point end-point"></view>
                        <view class="location-content">
                            <text class="location-text">{{ order.destinationAddress }}</text>
                        </view>
                    </view>
                </view>

                <!-- 备注信息 -->
                <view class="remark-info">
                    <text class="remark-label">备注：</text>
                    <text class="remark-text">{{ order.remark }}</text>
                </view>

                <!-- 订单金额 -->
                <!--   <view class="order-amount">
                    <text class="amount-label">订单金额：</text>
                    <text class="amount-value">¥{{ order.price || '0.00' }}</text>
                </view> -->

                <!-- 操作按钮 -->
                <view class="order-actions">
                    <!-- 确认接单按钮 -->
                    <button class="action-btn confirm-btn" @click="confirm(order)" v-if="order.acceptOrderState == 0">
                        确认接单
                    </button>
                    <!--  -->
                    <button class="action-btn confirm-btn" v-else-if="!order.confirmArrivalPickUpPointTime"
                        @click="confirmUpPoint(order)">
                        确认到达上车点
                    </button>
                    <button class="action-btn view-btn" @click="startOrder(order)"
                        v-else-if="order.orderState == 20 && order.acceptOrderState == 1">
                        开始行程
                    </button>
                    <button class="action-btn danger-btn" @click="endOrder(order)" v-if="order.orderState == 30">
                        结束行程
                    </button>
                </view>
            </view>
        </view>
    </view>
    <!-- 图片选择弹窗 -->
    <uni-popup ref="imagePopup" type="center" @close="resetImageModal">
        <div class="image-modal">
            <div class="modal-header">
                <h3>{{ currentAction === 'confirmUpPoint' ? '确认到达上车点' : '结束行程' }}</h3>
            </div>
            <div class="modal-content">
                <div class="image-selector">
                    <div class="image-grid">
                        <div class="image-item" v-for="(item, index) in selectedImages" :key="index">
                            <img :src="item.filePath" alt="" class="selected-image">
                            <view class="delete-btn" @click="deleteImage(index)">×</view>
                        </div>
                        <div class="add-image" v-if="selectedImages.length < maxImages" @click="chooseImages">
                            <span class="add-icon">+</span>
                            <span class="add-text">添加图片</span>
                        </div>
                    </div>
                    <div class="image-count">{{ selectedImages.length }}/{{ maxImages }}</div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="cancel-btn" @click="imagePopup.close()">取消</button>
                <button class="confirm-btn" @click="submitImages" :disabled="selectedImages.length === 0">确定</button>
            </div>
        </div>
    </uni-popup>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { queryDriverOrderInfo, startRouteOperation, endRouteOperation, confirmAcceptOrder, uploadPhoto, confirmArrivalPickUpPoint } from '@/api'
import { onPullDownRefresh, onReachBottom, onLoad } from '@dcloudio/uni-app'
import { formatTime } from '@/utils'
import { orderTypeMap, orderStatusMap } from '@/utils/constants'

// 图片选择弹窗
const imagePopup = ref(null)
const selectedImages = ref([]) // 用于追踪图片上传状态的对象数组
const currentOrder = ref(null)
const currentAction = ref('') // 'confirmUpPoint' or 'endOrder'
const maxImages = ref(3) // 最大选择图片数量

const phone = (mobile) => {
    if (!mobile) return
    uni.makePhoneCall({ phoneNumber: mobile })
}

const previewImage = (url, fileResponseList, orderNode) => {
    uni.previewImage({
        urls: fileResponseList.filter(x => x.orderNode == orderNode).map(x => 'http://8.155.170.55' + x.filePath),
        current: ('http://8.155.170.55' + url)
    })
}
// 选择图片
const chooseImages = () => {
    const remaining = maxImages.value - selectedImages.value.length
    if (remaining <= 0) return

    uni.chooseImage({
        count: remaining, // 最多选择剩余数量
        sizeType: ['compressed'], // 压缩图片
        crop: { quality: 50 },
        sourceType: ['camera', 'album'], // 可选择拍照或相册
        success: (chooseRes) => {
            // 遍历选择的图片，逐一上传
            chooseRes.tempFilePaths.forEach(filePath => {
                // 添加到选中图片列表，标记为未上传
                selectedImages.value.push({
                    filePath,
                    uploaded: false,
                    data: null
                })

                // 立即上传当前图片
                uploadPhoto(filePath)
                    .then(res => {
                        if (res.code === 200 && res.data) {
                            // 找到对应图片并标记为上传成功
                            const imgItem = selectedImages.value.find(item => item.filePath === filePath)
                            if (imgItem) {
                                imgItem.uploaded = true
                                imgItem.data = res.data
                            }
                            uni.showToast({ title: '图片上传成功', icon: 'none' })
                        } else {
                            uni.showToast({ title: res.msg || '图片上传失败', icon: 'none' })
                            // 移除上传失败的图片
                            const index = selectedImages.value.findIndex(item => item.filePath === filePath)
                            if (index !== -1) {
                                selectedImages.value.splice(index, 1)
                            }
                        }
                    })
                    .catch(error => {
                        uni.showToast({ title: '图片上传失败', icon: 'none' })
                        // 移除上传失败的图片
                        const index = selectedImages.value.findIndex(item => item.filePath === filePath)
                        if (index !== -1) {
                            selectedImages.value.splice(index, 1)
                        }
                    })
            })
        }
    })
}

// 删除选择的图片
const deleteImage = (index) => {
    selectedImages.value.splice(index, 1)
}

// 重置弹窗
const resetImageModal = () => {
    selectedImages.value = []
    currentOrder.value = null
    currentAction.value = ''
}

// 提交图片
const submitImages = () => {
    // 过滤出已上传成功的图片
    const uploadedImages = selectedImages.value.filter(item => item.uploaded)
    if (uploadedImages.length === 0 || !currentOrder.value) return
    uni.showLoading({ title: '正在处理...' })

    // 收集已上传的文件信息
    const fileRequestList = uploadedImages.map(item => item.data)

    // 根据当前操作调用不同的API
    let apiPromise
    if (currentAction.value === 'confirmUpPoint') {
        apiPromise = confirmArrivalPickUpPoint({
            orderUuid: currentOrder.value.orderUuid,
            fileRequestList
        })
        params.orderState = 30
    } else if (currentAction.value === 'endOrder') {
        apiPromise = endRouteOperation({
            orderUuid: currentOrder.value.orderUuid,
            fileRequestList
        })
        params.orderState = 40
    }

    apiPromise
        .then(apiRes => {
            if (apiRes.code === 200) {
                uni.hideLoading()
                uni.showToast({
                    title: currentAction.value === 'confirmUpPoint' ? '确认到达上车点成功' : '结束行程成功',
                    icon: 'none'
                })
                // 刷新订单列表
                params.pageNum = 1
                orders.value = []
                loadOrders()
                // 关闭弹窗
                imagePopup.value.close()
                // 重置弹窗
                resetImageModal()
            } else {
                throw new Error(apiRes.msg || '操作失败')
            }
        })
        .catch(error => {
            uni.hideLoading()
            uni.showToast({ title: error.message || '操作失败', icon: 'none' })
        })
}

// 订单分类数据
const categories = [
    // { label: '待分配', value: 10 },
    { label: '待进行', value: 20 },
    { label: '进行中', value: 30 },
    { label: '已完成', value: 40 },
    // { label: '停止服务', value: 50 }
]
onLoad((options) => {
    console.log(options)
    if (options.status) {
        params.orderState = Number(options.status)
    }
})
// 请求参数
const params = reactive({
    orderState: 20,
    pageNum: 1,
    pageSize: 10
})

// 订单数据
const orders = ref([])
const loading = ref(false)
const total = ref(0)
const isRefresh = ref(false)


// 切换分类
const changeCategory = (value) => {
    if (params.orderState === value) return
    params.orderState = value
    // 重置并重新加载订单
    params.pageNum = 1
    orders.value = []
    loadOrders()
}

const confirmUpPoint = (order) => {
    currentOrder.value = order
    currentAction.value = 'confirmUpPoint'
    imagePopup.value.open()
}
//                     } else {
//                         uni.showToast({ title: confirmRes.msg || '确认到达上车点失败', icon: 'none' })
//                     }
//                 })
//                 .catch((error) => {
//                     uni.hideLoading()
//                     console.error('确认到达上车点失败:', error)
//                 })
//         },
//         fail: (error) => {
//             console.error('选择照片失败:', error)
//             uni.showToast({ title: '选择照片失败', icon: 'none' })
//         }
//     })
// }

const confirm = (order) => {
    confirmAcceptOrder({
        orderUuid: order.orderUuid
    }).then(res => {
        if (res.code === 200) {
            uni.showToast({
                title: '确认接单成功',
                icon: 'none'
            })
            // 刷新订单列表
            params.pageNum = 1
            orders.value = []
            loadOrders()
        } else {
            uni.showToast({
                title: res.msg || '确认接单失败',
                icon: 'none'
            })
        }
    })
}

const startOrder = (order) => {
    startRouteOperation({
        orderUuid: order.orderUuid
    }).then(res => {
        if (res.code === 200) {
            uni.showToast({
                title: '行程开始成功',
                icon: 'none'
            })
            // 刷新订单列表
            params.orderState = 30
            params.pageNum = 1
            orders.value = []
            loadOrders()
        } else {
            uni.showToast({
                title: res.msg || '行程开始失败',
                icon: 'none'
            })
        }
    })
}

const endOrder = (order) => {
    currentOrder.value = order
    currentAction.value = 'endOrder'
    imagePopup.value.open()
}
//         }
//     })
// }

// 加载订单数据
const loadOrders = async () => {
    if (loading.value) return

    loading.value = true
    try {
        // 调用API获取订单数据
        const response = await queryDriverOrderInfo(params)
        if (isRefresh.value) {
            isRefresh.value = false
            uni.stopPullDownRefresh()
            uni.showToast({
                title: '刷新成功',
                icon: 'none'
            })
        }
        if (response.code === 200) {
            const list = response.data.list || []

            if (params.pageNum === 1) {
                orders.value = list
            } else {
                orders.value = [...list.value, ...list]
            }

            total.value = response.data.total
        } else {
            uni.showToast({
                title: response.message || '获取订单失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('加载订单失败:', error)
    } finally {
        loading.value = false;
        isRefresh.value = false
        uni.stopPullDownRefresh()
    }
}

// 加载更多订单
onReachBottom(() => {
    if (orders.value.length >= total.value) {
        uni.showToast({
            title: '没有更多订单了',
            icon: 'none'
        })
        return
    }
    params.pageNum++;
    loadOrders()
})

// 查看订单详情
const viewOrderDetail = (order) => {
    uni.showToast({
        title: '查看订单详情',
        icon: 'none'
    })
    // 这里可以跳转到订单详情页面
    // uni.navigateTo({
    //   url: `/pages/orderDetail/index?id=${order.orderId}`
    // })
}
onPullDownRefresh(() => {
    isRefresh.value = true
    params.pageNum = 1
    loadOrders()
})
// 页面加载时获取数据
onMounted(() => {
    loadOrders()
})
</script>

<style scoped>
.order-container {
    min-height: 100vh;
    background-color: #f5f5f5;
}

.page-header {
    background-color: #fff;
    padding: 16px 20px;
    border-bottom: 1px solid #e0e0e0;
    text-align: center;
}

.header-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.category-bar {
    display: flex;
    background-color: #fff;
    border-bottom: 1px solid #e0e0e0;
    margin-bottom: 10px;
}

.category-item {
    flex: 1;
    padding: 16px 0;
    text-align: center;
    position: relative;
}

.category-text {
    font-size: 14px;
    color: #666;
}

.category-item.active .category-text {
    color: #1989fa;
    font-weight: 500;
}

.category-item.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 25%;
    width: 50%;
    height: 3px;
    background-color: #1989fa;
    border-radius: 1.5px;
}

.order-list {
    padding: 0 10px;
}

.loading-container,
.empty-container {
    padding: 40px 0;
    text-align: center;
    color: #999;
    font-size: 14px;
}

.order-card {
    background-color: #fff;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
}

.order-type .type-tag {
    font-size: 12px;
    padding: 2px 8px;
    background-color: #e8f3ff;
    color: #1989fa;
    border-radius: 4px;
}

.order-status .status-text {
    font-size: 14px;
    color: #1989fa;
}

.info-value.phone {
    color: #1989fa;
}

.info-value .img-info {
    height: 140px;
    background-color: #e2e2e2;
    width: 100px;
    margin-right: 10px;
}

.order-info {
    margin-bottom: 10px;
}

.info-row {
    display: flex;
    margin-bottom: 6px;
    font-size: 14px;
}

.info-label {
    color: #999;
    margin-right: 5px;
    min-width: 70px;
}

.info-value {
    color: #333;
    flex: 1;
}

.route-info {
    margin: 15px 0;
    padding-left: 10px;
    position: relative;
}

.location-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
}

.location-point {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    margin-right: 10px;
    margin-top: 4px;
}

.start-point {
    background-color: #1989fa;
}

.end-point {
    background-color: #67c23a;
}

.location-content {
    flex: 1;
}

.location-text {
    font-size: 14px;
    color: #333;
    line-height: 1.4;
}

.location-line {
    position: absolute;
    left: 5px;
    top: 16px;
    width: 2px;
    height: calc(100% - 28px);
    background-color: #e0e0e0;
}

/* 图片选择弹窗样式 */
.image-modal {
    width: 90%;
    max-width: 500px;
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
}

.image-modal .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.image-modal .modal-header h3 {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.image-modal .close-btn {
    width: 36px;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5f5f5;
    border: none;
    border-radius: 50%;
    font-size: 24px;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
}

.image-modal .close-btn:hover {
    background-color: #e0e0e0;
    color: #333;
}

.image-modal .image-selector {
    margin-bottom: 20px;
}

.image-modal .image-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 12px;
    width: 250px;
}

.image-modal .image-item {
    width: calc(50% - 9px);
    aspect-ratio: 1;
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.image-modal .selected-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-modal .delete-btn {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 24px;
    height: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 0, 0, 0.8);
    border: none;
    border-radius: 50%;
    font-size: 16px;
    color: #fff;
    cursor: pointer;
    transition: all 0.3s ease;
}

.image-modal .delete-btn:hover {
    background-color: rgba(255, 0, 0, 1);
    transform: scale(1.1);
}

.image-modal .add-image {
    width: calc(50% - 9px);
    aspect-ratio: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #f5f5f5;
    border: 2px dashed #ccc;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.image-modal .add-image:hover {
    background-color: #e0e0e0;
    border-color: #999;
}

.image-modal .add-icon {
    font-size: 32px;
    color: #999;
    margin-bottom: 4px;
}

.image-modal .add-text {
    font-size: 12px;
    color: #999;
}

.image-modal .image-count {
    font-size: 14px;
    color: #666;
    text-align: right;
    margin-top: 8px;
}

.image-modal .modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}

.image-modal .cancel-btn,
.image-modal .confirm-btn {
    padding: 10px 20px;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
}

.image-modal .cancel-btn {
    background-color: #f5f5f5;
    color: #333;
}

.image-modal .cancel-btn:hover {
    background-color: #e0e0e0;
}

.image-modal .confirm-btn {
    background-color: #007aff;
    color: #fff;
}

.image-modal .confirm-btn:hover {
    background-color: #0056b3;
}

.image-modal .confirm-btn:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}

.remark-info {
    background-color: #f8f8f8;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 10px;
}

.remark-label {
    color: #999;
    font-size: 13px;
    margin-right: 5px;
}

.remark-text {
    color: #666;
    font-size: 13px;
    flex: 1;
}

.order-amount {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-bottom: 15px;
}

.amount-label {
    font-size: 14px;
    color: #666;
    margin-right: 5px;
}

.amount-value {
    font-size: 16px;
    font-weight: 600;
    color: #e64340;
}


.flight-number {
    font-size: 26rpx;
    color: #333;
    font-weight: 500;
    background-color: #f5f5f5;
    padding: 4rpx 16rpx;
    border-radius: 16rpx;
}

.order-actions {
    display: flex;
    gap: 20rpx;
    /* justify-content: flex-end; */
}

.action-btn {
    font-size: 16px;
    padding: 10rpx 40rpx;
    margin: 0px;
    border-radius: 4px;
    background-color: transparent;
}

.view-btn {
    color: #1989fa;
    border: 1px solid #1989fa;
}

.danger-btn {
    color: #e64340;
    border: 1px solid #e64340;
}

.load-more {
    text-align: center;
    padding: 15px 0;
    color: #999;
    font-size: 14px;
}

.load-more:active {
    background-color: rgba(0, 0, 0, 0.05);
}
</style>
